package service;

import java.io.IOException;
import java.net.URL;
import java.net.UnknownHostException;

import model.QuestionModel;

import org.jsoup.nodes.Document;
import entity.Question;

public class GetLanguageThread extends Thread {

	Question obj;
	String lang;
	String socket;
	QuestionModel questionModel;

	public GetLanguageThread(Question question, String language, String socket) {
		this.obj = question;
		this.lang = language;
		this.socket = socket;
		start();
	}

	public void run() {
		try {
			Question question = new Question();
			Document doc = null;
			URL dataURL;
			dataURL = new URL(obj.getUrl().replaceAll("efreedom.com",
					lang + ".efreedom.com"));			
			String content = "";
			try {
				doc = util.SocketContentHandle.getSiteContentBySocket(
						"efreedom.com", "", dataURL.toString(), socket);
			} catch (UnknownHostException ex) {
				System.out
						.println("UnknownHostException occur when get question url");
			} catch (IOException ex) {
				System.out.println("IOException occur when get question url");
			}

			question.setTitle(doc.select("#questionTitle").html());
			content = new String(doc.select("#fullQuestionBody").html());
			question.setContent(content);
			content = new String(doc.select("#fullAnswerBody").html());
			question.setContentAnswer(content);
			question.setLang(lang);
			question.setAlias(obj.getAlias());
			question.setAliasAuthor(obj.getAliasAuthor());
			question.setAliasAuthorAnswer(obj.getAliasAuthorAnswer());
			question.setDoc(obj.getDoc());
			question.setLastUpdateDate(obj.getLastUpdateDate());
			question.setOtherTags(obj.getOtherTags());
			question.setTags(obj.getTags());
			question.setUrl(obj.getUrl());
			question.setHadContent(1);
			if (question.isValid()) {
				questionModel = new QuestionModel();
				questionModel.save(question);
				System.out.println("Language : " + lang + " added ! Socket : "
						+ socket);
			} else {
				System.out.println("Language : " + lang + " error occur !");
			}
			Thread.currentThread().interrupt();

		} catch (Exception e) {
			System.out.println(e.toString());
		}
	}
}
